<?php
namespace app\api\controller\v1;

use think\Controller;
use think\Request;
use think\Db;
use think\Validate;

class Checkin extends Controller
{
    protected $noNeedLogin = '*';
    protected $noNeedRight = '*';

    public function checkInOut(Request $request)
    {
        $data = $request->post();

        $validate = new Validate();
        $validate->rule([
            'classes_id'   => 'require|number',
            'classes_type' => 'require|in:1,2',
            'user_id'      => 'require|number',
        ]);
        if (!$validate->check($data)) {
            return json(['code' => 0, 'msg' => $validate->getError(), 'data' => []]);
        }

        $today = date('Y-m-d');
        $now   = date('Y-m-d H:i:s');
//        $today="2025-11-24";
//        $now="2025-11-24 09:50:00";

        // 查当天未签退记录
        $row = Db::name('user_clock')
            ->where('classes_id', intval($data['classes_id']))
            ->where('user_id', intval($data['user_id']))
            ->where('date', $today)
            ->where('delete_time', null)
            ->order('id', 'desc')
            ->find();

        // 获取当天课程时段
        $nowTs = strtotime($now);
        $schedules = Db::name('fa_course_table_autoplan')
            ->where('classes_id', intval($data['classes_id']))
            ->where('date', $today)
            ->order('start_time', 'asc')
            ->select();


        // 选择符合当前时间的课程时段（如果有多个时段，以当前时间落入规则范围的为准）
        $match = null;
        foreach ($schedules as $sch) {
            $startTs = strtotime($today . ' ' . ($sch['start_time'] ?? '00:00:00'));
            $endTs   = strtotime($today . ' ' . ($sch['end_time'] ?? '23:59:59'));
            // 任一课程的总允许窗口：上课前1小时至下课后2小时
            if ($nowTs >= ($startTs - 3600) && $nowTs <= ($endTs + 7200)) {
                $match = ['startTs' => $startTs, 'endTs' => $endTs];
                break;
            }
        }

        if (!empty($match) && (!$row || !empty($row['checkout_time']))) {

            // 校验签到时间窗：上课前1小时 到 下课前
            if (!($nowTs >= ($match['startTs'] - 3600) && $nowTs <= $match['endTs'])) {
                return json(['code' => 200, 'msg' => '未到签到打卡时间（上课前1小时至下课前）', 'data' => ['rule' => '签到：上课前1小时至下课前']]);
            }

            // 签到
            $insert = [
                'classes_id'   => intval($data['classes_id']),
                'classes_type' => intval($data['classes_type']),
                'user_id'      => intval($data['user_id']),
                'date'         => $today,
                'checkin_time' => $now,
                'clock_time'   => $now,
                'checkout_time'=> null,
                'latitude'     => isset($data['latitude']) ? $data['latitude'] : null,
                'longitude'    => isset($data['longitude']) ? $data['longitude'] : null,
                'location'     => isset($data['location']) ? $data['location'] : null,
                'remarks'      => isset($data['remarks']) ? $data['remarks'] : null,
                'status'       => 1,
                'weigh'        => 0,
                'create_time'  => $now,
                'update_time'  => $now,
                'delete_time'  => null,
            ];
            Db::name('user_clock')->insert($insert);
            //加签到积分
            Db::name('user')
                ->where('id', intval($data['user_id']))
                ->update([
                    'score' => Db::raw('score + 3'),
                ]);
            Db::name('user_points')->insert([
                'user_id'    => intval($data['user_id']),
                'classes_id' => intval($data['classes_id']),
                'type'       => 1,
                'points'     => 3,
                'date'       => $today,
                'remarks'    => '签到',
                'create_time'=> strtotime($now),
                'update_time'=> strtotime($now),
            ]);
            return json(['code' => 200, 'msg' => '签到成功', 'data' => ['action' => 'checkin', 'time' => $now]]);
        }

        // 校验签退时间窗：下课前10分钟 到 下课后2小时
        if (!empty($match) && !($nowTs >= ($match['endTs'] - 600) && $nowTs <= ($match['endTs'] + 7200))) {
            return json(['code' => 0, 'msg' => '未到签退打卡时间（下课前10分钟至下课后2小时）', 'data' => ['rule' => '签退：下课前10分钟至下课后2小时']]);
        }
        if (!empty($match) && (!empty($row) || !empty($row['checkin_time']))) {
            // 签退
            Db::name('user_clock')
                ->where('id', $row['id'])
                ->update([
                    'checkout_time' => $now,
                    'update_time' => $now,
                ]);
            //加签退积分
            Db::name('user')
                ->where('id', intval($data['user_id']))
                ->update([
                    'score' => Db::raw('score + 3'),
                ]);
            Db::name('user_points')->insert([
                'user_id' => intval($data['user_id']),
                'classes_id' => intval($data['classes_id']),
                'type' => 1,
                'points' => 3,
                'remarks' => '签退',
                'date' => $today,
                'create_time' => strtotime($now),
                'update_time' => strtotime($now),
            ]);
            return json(['code' => 200, 'msg' => '签退成功', 'data' => ['action' => 'checkout', 'time' => $now]]);
        }
        return json(['code' => 200, 'msg' => '', 'data' => ['action' => '', 'time' => $now]]);
    }
}